/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-wechatpush
*
* @File name : HttpsUtil.java
*
* @Author : Administrator
*
* @Date : 2017年7月13日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年7月13日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/
	
package com.yonyou.gmmc.service.wechatpush.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import org.apache.log4j.Logger;


/**
*
* @author Administrator
* TODO description
* @date 2017年7月13日
*/

public class HttpsUtil {
    
    private static Logger logger = Logger.getLogger(HttpsUtil.class);
    
    public static  String connectHttpsByPost(String path, String KK, String url) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        logger.info("path为："+path);
        logger.info("KK为："+KK);
        logger.info("url为："+url);
        URL urlObj = new URL(path);
        URL fileUrl = new  URL(url);  
        HttpURLConnection   urlcon=(HttpURLConnection)fileUrl.openConnection();     
        urlcon.connect();
        //根据响应获取文件大小   
        int length=urlcon.getContentLength();  
        logger.info("根据响应获取文件大小 :"+length);
        //连接
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        String result = null;
        con.setDoInput(true);

        con.setDoOutput(true);

        con.setUseCaches(false); // post方式不能使用缓存

        // 设置请求头信息
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        // 设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type",
                "multipart/form-data; boundary="
                        + BOUNDARY);

        // 请求正文信息
        // 第一部分：
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // 必须多两道线
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + length + "\";filename=\""

                + url.substring(url.lastIndexOf("/")+1) + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] head = sb.toString().getBytes("utf-8");
        // 获得输出流
        OutputStream out = new DataOutputStream(con.getOutputStream());
        // 输出表头
        out.write(head);
        
        InputStream inputStream = null;
        inputStream = urlcon.getInputStream();
        //filestore

        byte[] buffers = new byte[4096];
        int n = 0;
        while (-1 != (n = inputStream.read(buffers))) {
            out.write(buffers, 0, n);
        }

        // 结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
        out.write(foot);
        out.flush();
        out.close();
        
        urlcon.disconnect();  
        
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        try {
            // 定义BufferedReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            if (result == null) {
                result = buffer.toString();
            }
        } catch (IOException e) {
            logger.info("发送POST请求出现异常！" + e);
            logger.info("操作异常："+e.getMessage(),e);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return result;
    }
}
